package com.bbcare.followup.plat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.followup.plat.entity.AuAccount;
import com.bbcare.followup.plat.store.ibatis.IAuAccountDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZCL on 2019/6/4.
 */
@Controller
@RequestMapping("/change/password")
public class ChangePasswordController {
    private final Log logger = LogFactory.getLog(PatientController.class);

    @Autowired
    private IAuAccountDAO auAccountDao;

    // 根据登陆手机号修改密码
    @ResponseBody
    @RequestMapping("/update")
    public ResultModel<String> getTenantQueueTemp(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in update----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String phoneNo = jsonData.getString("phoneNo");
        if (null == phoneNo || "".equals(phoneNo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入登陆手机号或值为空！"));
        }

        String passWord = jsonData.getString("passWord");
        if (null == passWord || "".equals(passWord)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入要修改的密码或值为空！"));
        }

        AuAccount auAccount = auAccountDao.selectAccountByPhoneNo(phoneNo);

        if (auAccount == null) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询无此手机号记录！"));
        }

        passWord = ChangePasswordController.Encrept(passWord);

        Map paramMap = new HashMap();

        paramMap.put("phoneNo", phoneNo);
        paramMap.put("passWord", passWord);

        int i = auAccountDao.updateAccountByPhoneNo(paramMap);

        String msg = "";

        if (i > 0) {
            msg = "更新成功！";
        } else {
            msg = "更新失败！";
        }

        return new ResultModel<String>(msg);
    }


    /**
     * SHA-256 和 SHA-512j加密 输入参数：
     *
     * @param strText
     *            String 需要加密的字符串
     * @param strType
     *            String SHA-256 和 SHA-512 两种 Hash 算法 输出参数
     * @return  加密后的出参
     *            String 异或运算后的字符串
     * @author wuyz
     * @throws UnsupportedEncodingException
     * @throws Exception
     * @createTime 2017.06.13
     **/
    public static String changeToSHA(String strText, String strType) throws UnsupportedEncodingException {

        // 返回值
        String strResult = "";

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes("UTF-8"));
                // 得到 byte 类型结果
                byte byteBuffer[] = messageDigest.digest();
                BASE64Encoder encode = new BASE64Encoder();
                strResult = encode.encode(byteBuffer);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        // System.out.println(strResult);
        strResult = strResult.toLowerCase();
        return strResult;
    }

    /**
     * md5加密函数 入参参数描述：
     *r
     * @param sourceStr
     *            String 需要加密的字符串
     * @param flag
     *            int 需要加密的位数：（1）32：返回32位加密串 （2）16：返回16位加密串 返回参数：
     * @return sourceStr String MD5加密后的字符串
     * @createTime 2017.06.13
     * @author wuyz
     *
     **/

    public static String MD5Encrept(String sourceStr, int flag) throws Exception {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            if (flag == 32) {
                result = buf.toString();
            } else {
                result = buf.toString().substring(8, 24);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new NoSuchAlgorithmException(e.toString());
        }

        return result;
    }

    public static String Encrept(String password) throws Exception {
        password = password+ConstantParams.SECRET_KEY;
        password = ChangePasswordController.changeToSHA(password,ConstantParams.COMMON_SHA_256);
        password = MD5Encrept(password,ConstantParams.COMMON_MD5_32);
        return password;
    }
}
